package com.lcf.app.mongodb.controller;

import com.lcf.app.mongodb.model.User;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;

/**
 * @author ChenFei
 * @date 2021/12/3
 */
@RestController
@RequestMapping("mongodb")
public class MongoDBController {

    @Resource
    private MongoTemplate mongoTemplate;

    @RequestMapping("save")
    public User user(@RequestParam("name") String name) {
        User user = new User()
                .setName(name)
                .setAge(18)
                .setHeight(185.0)
                .setWeight(85.0)
                .setBirthday(LocalDate.now());
        return mongoTemplate.save(user);
    }

    @RequestMapping("findAll")
    public List<User> findAll() {
        return mongoTemplate.findAll(User.class);
    }

    @RequestMapping("update")
    public Long update(@RequestParam("id") String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        Update update = new Update();
        update.set("name", "ZhangSan");
        UpdateResult updateResult = mongoTemplate.updateMulti(query, update, User.class);
        //获取更新所修改的文档数量
        return updateResult.getModifiedCount();
    }

    @RequestMapping("findById/{id}")
    public User findById(@PathVariable("id") String id) {
        return mongoTemplate.findById(id, User.class);
    }

    @RequestMapping("removeById/{id}")
    public Long remove(@PathVariable("id") String id) {
        DeleteResult deleteResult = mongoTemplate.remove(new User().setId(id));
        return deleteResult.getDeletedCount();
    }

    @RequestMapping("page")
    public List<User> page(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize) {
        Integer offset = (pageNum - 1) * pageSize;
        Query query = new Query();
        Criteria criteria = new Criteria();//查询条件构造器
        query.addCriteria(criteria);
        //分页
        query.limit(pageSize).skip(offset);
        return mongoTemplate.find(query, User.class);
    }

}
